package com.iwop.moto.controller;

import com.iwop.moto.comm.Comm;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.model.FErrorLog;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.service.FErrorLogService;
import com.iwop.moto.utils.http.SessionUtils;
import com.iwop.moto.utils.stringUtil.JsonUtils;
import com.iwop.moto.utils.weixin.WeixinUtil;
import org.apache.htrace.fasterxml.jackson.core.JsonProcessingException;
import org.apache.htrace.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 基础Controller
 * @author huyuangui
 * @time 2015-9-23 下午02:51:15
 */
public class BaseController {

	@Autowired
	private FErrorLogService fErrorLogService;

	/**
	 * 日志
	 */
	public static Logger log = Logger.getLogger(BaseController.class);
	/**
	 * 获取Session 
	 * 当Session要换成其他来维持时，便于统一修改Session 
	 * @return
	 */
	public  HttpSession getSession(){	
        HttpServletRequest requst = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();        
		return requst.getSession();
	}
	public  void setKeyValueToSession(String key,Object value){
		SessionUtils.setKeyValue(key,value);
//		getSession().setAttribute(key, value);
		//Comm.map.put(key, value);
	}
	public  Object getValueFromSession(String key){
//		return getSession().getAttribute(key);
		return SessionUtils.getValueFromSession(key);
		//return Comm.map.get(key);
	}
	public  Object putValueFromSession(String key,Object value,int second){
//		return getSession().getAttribute(key);
		return SessionUtils.putValueFromSession(key,value,second);
		//return Comm.map.get(key);
	}

	public  void delValueFromSession(String key){
		 SessionUtils.removeRedisByKey(key);
	}

	public String getUserId(){
		return getRequest().getParameter("session_id");
	}
	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}

	public Object getParam(String name){
		return getRequest().getParameter(name);
	}

	public SuperRecordModel getSRModel(){
		return new SuperRecordModel(this.getRequest());
	}

	//数据拷贝
	public SuperRecordModel copyModel(SuperRecordModel fromSuperRecordModel,SuperRecordModel toSuperRecordModel,String keys){

		if(keys==null || keys.length()<1) {
			return fromSuperRecordModel;
		}
		String []key=keys.split(",");
		for (int i=0;i< key.length;i++){
			toSuperRecordModel.put(key[i], fromSuperRecordModel.get(key[i]));
		}
		return  toSuperRecordModel;
	}
	public ResultModel getErr(String mem){
		ResultModel rm = new ResultModel();
		rm.setCode(0);
		rm.setMem(mem);
		return rm;
	}

	public ResultModel getSucceed(Object obj){
		ResultModel rm = new ResultModel();
		rm.setCode(1);
		rm.setData(obj==null?null:toJsonString(obj));
		return rm;
	}

	public ResultModel getSucceed(Object obj,String mem ) {
		ResultModel rm = new ResultModel();
		rm.setCode(1);
		rm.setMem(mem);
		if(obj != null){
			rm.setData(toJsonString(obj));
		}
		return rm;
	}

	public ResultModel getSucceed(Object obj,String mem,String annex ) {
		ResultModel rm = new ResultModel();
		rm.setCode(1);
		rm.setMem(mem);
		rm.setAnnex(annex);
		if(obj != null){
			rm.setData(toJsonString(obj));
		}
		return rm;
	}

	public ResultModel getModelByString(String result){
		if (result.equals(ErrCode.SUCCEED)){
			return getSucceed(result);
		}else {
			return getErr(result);
		}
	}

	public String toJsonString(Object obj){
		ObjectMapper mapper = new ObjectMapper();
		String  str = "";
		try {
			str =  mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return str;
	}

	public ModelAndView errorMv(String str){
		ModelAndView mv = new ModelAndView();
		mv.addObject("error_msg", str);
		mv.setViewName("error");
		return mv;
	}

	/**
	 * @功能: 获取微信AccessToken
	 */
	public Map getWxAccessToken(){
		try {
			Map wxAccessToken = getValueFromSession(Comm.REDIS_WEIXIN_ACCESS_TOKEN_KEY)==null?null:
					JsonUtils.toMap(getValueFromSession(Comm.REDIS_WEIXIN_ACCESS_TOKEN_KEY).toString());
			if(wxAccessToken == null){
				System.out.println("Token不存在,重新获取!");
				wxAccessToken = WeixinUtil.getWxAccessToken();
				putValueFromSession(Comm.REDIS_WEIXIN_ACCESS_TOKEN_KEY,wxAccessToken,3600);
			}
			return wxAccessToken;
		}catch (Exception e){
			e.printStackTrace();
			Map wxAccessToken = WeixinUtil.getWxAccessToken();
			putValueFromSession(Comm.REDIS_WEIXIN_ACCESS_TOKEN_KEY,wxAccessToken,3600);
			return wxAccessToken;
		}
	}

	/**
	 * @功能: 获取微信ticket
	 */
	public Map getWxTicket(){
		try {
			Map wxAccessToken = getWxAccessToken();
			Map wxTicket = WeixinUtil.getWxTicket(wxAccessToken.get("access_token") == null ? "" : wxAccessToken.get("access_token").toString());
			if(!wxTicket.get("errcode").equals(0)){
				System.out.println("Token异常,重新获取!");
				wxAccessToken = WeixinUtil.getWxAccessToken();
				putValueFromSession(Comm.REDIS_WEIXIN_ACCESS_TOKEN_KEY, wxAccessToken, 3600);
				wxTicket = WeixinUtil.getWxTicket(wxAccessToken.get("access_token").toString());
			}
			return wxTicket;
		}catch (Exception e){
			e.printStackTrace();
			Map wxAccessToken = getWxAccessToken();
			putValueFromSession(Comm.REDIS_WEIXIN_ACCESS_TOKEN_KEY, wxAccessToken, 3600);
			Map wxTicket = WeixinUtil.getWxTicket(wxAccessToken.get("access_token").toString());
			return wxTicket;
		}
	}

	public void ErrorLog(Exception e,String ... params){
		FErrorLog errorLog = new FErrorLog();
		errorLog.setErrName(params.length==0?null:params[0]);
		errorLog.setErrData(params.length<2?null:params[1]);
		if(e!=null){
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			errorLog.setErrContent(sw.toString());
		}
		fErrorLogService.insert(errorLog);
	}

	public static Map<String, String> getRequestParams(HttpServletRequest request){

		Map<String, String> params = new HashMap<String, String>();
		if(null != request){
			Set<String> paramsKey = request.getParameterMap().keySet();
			for(String key : paramsKey){
				params.put(key, request.getParameter(key));
			}
		}
		return params;
	}

}